package com.example.blog.controller;

import com.example.blog.model.BlogInfo;
import com.example.blog.model.Result;
import com.example.blog.service.UserService;
import com.example.blog.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/blog")
@RestController
public class BlogController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getList")
    public List<BlogInfo>getList(){
        return userService.getList();

    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId,HttpServletRequest request) throws Exception {
        if(blogId==null){
            throw new Exception("id 不能为空");
        }
        BlogInfo blogInfo= userService.getBlogDetail(blogId);

        //作者ID
        Integer authorId = blogInfo.getUserId();
        //登录用户ID
        String jwtToken = request.getHeader("user_token");
        Integer loinUserId = JWTUtils.getUserIdFromToken(jwtToken);
        if(authorId!=null&&authorId==loinUserId){
            blogInfo.setLoginUser(true);
        }
        return blogInfo;

    }

    @RequestMapping("/add")
    public Result insert(String title, String content, HttpServletRequest request){
        //获取当前登录用户的ID
        String jwtToken = request.getHeader("user_token");
        Integer loinUserId = JWTUtils.getUserIdFromToken(jwtToken);
        if(loinUserId==null||loinUserId<1){
            return Result.fail("用户未登录");
        }

        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setUserId(loinUserId);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        userService.insertBlog(blogInfo);
        return Result.success(true);

    }
    @RequestMapping("/update")
    public Result update(@RequestBody BlogInfo blogInfo){
        userService.updateBlog(blogInfo);
        return Result.success(true);

    }
    @RequestMapping("/delete")
    public boolean delete(Integer blogId){
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);
        userService.updateBlog(blogInfo);
        return true;
    }
}
